package by.wind.drebedengi.asynctask;

import java.util.ArrayList;
import java.util.Calendar;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;

import by.wind.drebedengi.R;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.Constants;
import by.wind.drebedengi.datalayer.bean.Record;
import android.app.ProgressDialog;
import android.content.Context;

public class ReportingAllAsyncTask extends AbstractTask {

	protected ArrayList<Record> itsList = new ArrayList<Record>();
	
	public ReportingAllAsyncTask(Context aContext) {
		super(aContext);
		itsProgressMessage = itsContext.getString(R.string.task_reporting);
	}

	@Override
	public void setProgressTracker(IProgressTracker progressTracker) {
		itsProgressTracker = progressTracker;
		// Initialise progress tracker with current task state
		if (itsProgressTracker != null) {
		    itsProgressTracker.onProgress(itsProgressMessage);
		    if (itsResult != null) {
			itsProgressTracker.onComplete();
		    }
		}
		
	}

	@Override
	protected Boolean doInBackground(Long... params) {
		MyDatabaseHelper helper = new MyDatabaseHelper(itsContext);
		RuntimeExceptionDao<Record, Integer> recordDao = helper.getRecordDataDao();
    
    	try {
    		QueryBuilder<Record, Integer> queryBuilder = recordDao.queryBuilder();
        	Where<Record, Integer> where = queryBuilder.where();
        	where.eq(Record.IS_DUTY, false);
        	where.and();
        	Calendar cal = Calendar.getInstance();
        	cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1);
        	where.gt(Record.OPERATION_DATE, cal.getTime());
        	where.and();
        	queryBuilder.where().eq(Record.OPERATION_TYPE, Constants.OPERATION_INCOME).or().eq(Record.OPERATION_TYPE, Constants.OPERATION_WASTLE);
        	queryBuilder.orderBy(Record.OPERATION_DATE, false);
			PreparedQuery<Record> preparedQuery = queryBuilder.prepare();
			itsList = (ArrayList<Record>) recordDao.query(preparedQuery);
    	} catch( Exception ex) {
    		ex.printStackTrace();
    		return false;
    	}
			helper.close();
			return true;
	}
	
	public ArrayList<Record> getList() {
		return itsList;
	}

	@Override
	protected int getProgressType() {
		return ProgressDialog.STYLE_SPINNER;
	}

	@Override
	public String onErrorMessage() {
		return itsContext.getString(R.string.task_reporting_error);
	}
}
